package gocomm

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"regexp"
	"time"
)

type AddressInfo struct {
	Status int    `json:"status"`
	Result Result `json:"result"`
}

type Result struct {
	AddressComponent AddressComponent `json:"addressComponent"`
}

type AddressComponent struct {
	Province string `json:"province"`
	City     string `json:"city"`
	District string `json:"district"`
}

// 逆地址编码
// 根据 经纬度 找 城市
// localtion:=fmt.Sprintf("%.5f,%.5f",lat,longt)
// addressInfo,err:=utils.Reverse_geocoding("oOf9RvrejLXGuYbpdDlaiKIQtQZx7aNu",localtion)
func Reverse_geocoding(token string, locaiton string) (*AddressInfo, error) {

	// url:=`http://api.map.baidu.com/reverse_geocoding/v3/?ak=%s&output=json&coordtype=wgs84ll&location=31.318216,120.823634`
	url := fmt.Sprintf(`http://api.map.baidu.com/reverse_geocoding/v3/?ak=%s&output=json&coordtype=wgs84ll&location=%s`, token, locaiton)

	bytes, err := HTTPGet(url)
	if err != nil {
		return nil, err
	}

	var address AddressInfo
	err = json.Unmarshal(bytes, &address)
	if err != nil {
		return nil, err
	}
	return &address, nil

}

func GeneratorRandomAlpabet(num int) string {
	const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	rand.Seed(time.Now().UnixNano())
	b := make([]byte, 6)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	return string(b)
}

func GetNumFromSms(text string) string {
	regex := `\d{4,7}`
	matches := regexp.MustCompile(regex).FindAllString(text, -1)

	if len(matches) == 0 {
		return ""
	} else {
		return matches[0]
	}
}
